package com.jilefojing.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jilefojing.beans.data.web.request.RegisterRequest;
import com.jilefojing.beans.exception.UserContextException;
import com.jilefojing.beans.pojos.User;
import com.jilefojing.service.IRegisterService;
import com.jilefojing.service.IUserService;
import com.jilefojing.util.Detect;

@Service
public class RegisterService implements IRegisterService {
	@Autowired
	private IUserService userService;

	@Override
	public User register(RegisterRequest registerRequest)
			throws UserContextException {
		if (!Detect.checkMobileNumber(registerRequest.getTelphone())) {
			throw new UserContextException("[手机号输入有误]");
		}

		if (!Detect.notEmpty(registerRequest.getPassword())
				|| registerRequest.getPassword().trim().length() == 0) {
			throw new UserContextException("[密码不能为空]");
		}
		if (Detect.isContainChinese(registerRequest.getPassword())) {
			throw new UserContextException("[密码不能含有汉字]");
		}
		if (Detect.isContainSpecialCode(registerRequest.getPassword())) {
			throw new UserContextException("[密码不能含有特殊字符]");
		}
		if (registerRequest.getPassword().length() < 6
				|| registerRequest.getPassword().length() > 16) {
			throw new UserContextException("[密码:6-16个字符，区分大小写]");
		}
		if (!registerRequest.getPassword().equals(
				registerRequest.getPassword2())) {
			throw new UserContextException("[两次密码输入不一致]");
		}

		User record = new User();
		record.setTelphone(registerRequest.getTelphone());
		record.setPassword(registerRequest.getPassword());
		record.setNickname("极乐_"
				+ new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()));

		// TODO 注册待优化

		return userService.add(record, null);

	}

}
